package com.distribute.order.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.distribute.order.dao.JedisClient;
import com.distribute.order.pojo.BootstrapResult;
import com.distribute.pojo.Order;
import com.distribute.service.DbItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.distribute.order.service.OrderService;
import com.distribute.common.pojo.DistributeResult;
import com.distribute.common.util.HttpClientUtil;
import com.distribute.mapper.DbItemMapper;
import com.distribute.mapper.DbOrderItemMapper;
import com.distribute.mapper.DbOrderMapper;
import com.distribute.mapper.OrderMapper;
import com.distribute.pojo.DbItem;
import com.distribute.pojo.DbOrder;
import com.distribute.pojo.DbOrderItem;

/**
 * <p>
 * Title: OrderServiceImpl
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * </p>
 * 
 * @version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private DbOrderMapper dbOrderMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private DbOrderItemMapper dbOrderItemMapper;
	@Autowired
	private DbItemMapper itemMapper;
	@Autowired
	private JedisClient jedisClient;

	@Value("${ORDER_GEN_KEY}")
	private String ORDER_GEN_KEY;
	@Value("${ORDER_INIT_ID}")
	private String ORDER_INIT_ID;
	@Value("${ORDER_DETAIL_GEN_KEY}")
	private String ORDER_DETAIL_GEN_KEY;
	
	// Solr服务Base URL
	@Value("${SEARCH_MANAGER_BASE_URL}")
	private String SEARCH_MANAGER_BASE_URL;
	@Value("${SEARCH_IMPORT_ALL}")
	private String SEARCH_IMPORT_ALL;
	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	@Value("${REST_ITEM_BASEINFO_SYNC_URL}")
	private String REST_ITEM_BASEINFO_SYNC_URL;

	@Override
	public DistributeResult createOrder(DbOrder order, DbOrderItem orderItem) {
		// 向订单表中插入记录
		// 获得订单号
		String string = jedisClient.get(ORDER_GEN_KEY);
		if (StringUtils.isBlank(string)) {
			jedisClient.set(ORDER_GEN_KEY, ORDER_INIT_ID);
		}
		long orderId = jedisClient.incr(ORDER_GEN_KEY);
		// 补全pojo的属性
		order.setOrderId(orderId + "");
		// 状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
		//申请状态：1成功3审核中2失败
		order.setStatus(3);
		Date date = new Date();
		order.setCreateTime(date);
		order.setUpdateTime(date);
		// 0：未评价 1：已评价
		/* order.setBuyerRate(0); */
		// 向订单表插入数据
		dbOrderMapper.insert(order);
		// 插入订单明细
		// 补全订单明细
		// 取订单明细id
		long orderDetailId = jedisClient.incr(ORDER_DETAIL_GEN_KEY);
		orderItem.setId(orderDetailId + "");
		orderItem.setOrderId(orderId + "");
		System.out.println(
				"id:" + orderItem.getId() + "Itemid:" + orderItem.getItemId() + "ORDERid:" + orderItem.getOrderId());
		// 向订单明细插入记录
		dbOrderItemMapper.insert(orderItem);
		// 插入物流表
		// 补全物流表的属性
		/*
		 * orderShipping.setOrderId(orderId + ""); orderShipping.setCreated(date);
		 * orderShipping.setUpdated(date); orderShippingMapper.insert(orderShipping);
		 */
		Long[] ids = new Long[1];
		ids[0] = Long.parseLong(orderItem.getItemId());
		for (long id : ids) {
			DbItem item = itemMapper.selectByPrimaryKey(id);
			item.setStatus((byte) 2);
			itemMapper.updateByPrimaryKey(item);
			// Solr同步
			HttpClientUtil.doGet(SEARCH_MANAGER_BASE_URL + SEARCH_IMPORT_ALL);
			// redis缓存同步
			HttpClientUtil.doGet(REST_BASE_URL + REST_ITEM_BASEINFO_SYNC_URL + id);
		}
		// 申请成功后需要同步缓存，否则宠物状态仍是待领养
		
		return DistributeResult.ok(orderId);
	}

	@Override
	public DistributeResult getOrderByUserId(long userId, Integer page, Integer rows) {
		// 分页处理
		PageHelper.startPage(page, rows);
		List<Order> list = orderMapper.getOrderListByUserId(userId);
		PageInfo<Order> pageInfo = new PageInfo<>(list);
		BootstrapResult result = new BootstrapResult();
		result.setOrderList(list);
		// 此处获取的是总记录数，对于boostrap前端分页来说，还需要在controller中做处理（总记录数/）
		result.setTotalPages(pageInfo.getTotal());
		return DistributeResult.ok(result);
	}

	@Override
	public Order getOrderById(long orderId) {
		Order order = orderMapper.getOrderById(orderId);
		return order;
	}

}
